<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" id="upload" />
    <script>
      const ACCEPT = ["image/jpg", "image/png", "image/jpeg"];
      const MAXSIZE = 3 * 1024 * 1024;
      const MAXSIZE_STR = "3MB";

      function convertImageToBase64(file, callback) {
        let reader = new FileReader();
        reader.addEventListener("load", function (e) {
          // console.log(e.target.result)
          // console.log(reader.result)
          const base64Image = e.target.result;
          callback && callback(base64Image);
          reader = null;
        });
        reader.readAsDataURL(file);
      }

      function compress(base64Image, callback) {
        let maxW = 1024;
        let maxH = 1024;
        const image = new Image();
        image.addEventListener("load", function (e) {
          // 图片压缩比
          let ratio;
          // 是否需要压缩
          let needCompress = false;
          if (maxW < image.naturalWidth) {
            needCompress = true;
            ratio = image.naturalWidth / maxW;
            // 宽度压缩后，高度也要进行相应的压缩
            maxH = image.naturalHeight / ratio;
          }

          if (maxH < image.naturalHeight) {
            needCompress = true;
            ratio = image.naturalHeight / maxH;
            maxW = image.naturalWidth / ratio;
          }

          // 如果不需要压缩
          if (!needCompress) {
            maxW = image.naturalWidth;
            maxH = image.naturalWidth;
          }

          const canvas = document.createElement("canvas");
          canvas.setAttribute("id", "__compress__");
          canvas.width = maxW;
          canvas.height = maxH;
          canvas.style.visibility = "hidden";
          document.body.appendChild(canvas);

          const ctx = canvas.getContext("2d");
          ctx.clearRect(0, 0, maxW, maxH);
          ctx.drawImage(image, 0, 0, maxW, maxH);
          const compressImage = canvas.toDataURL("image/jpeg", 0.8);

          callback && callback(compressImage);
        //   const __image = new Image();
        //   __image.src = compressImage;
        //   document.body.appendChild(__image);
          canvas.remove();
        //   console.log(`压缩比:${image.src.length / __image.src.length}`);
        });
        image.src = base64Image;
        document.body.appendChild(image);
      }

      function uploadToServer(compressImage) {
        console.log("upload to server...");
      }

      /** @type {HTMLInputElement} */
      const upload = document.getElementById("upload");
      upload.addEventListener("change", function (e) {
        const [file] = e.target.files;
        if (!file) return;

        const { type: fileType, size: fileSize } = file;
        // 图片类型检查
        if (!ACCEPT.includes(fileType)) {
          alert(`不支持[${fileType}]文件类型`);
          upload.value = "";
          return;
        }

        // 图片容量检查
        if (fileSize > MAXSIZE) {
          alert(`文件超出[${MAXSIZE_STR}]`);
          upload.value = "";
          return;
        }

        // 压缩图片
        convertImageToBase64(file, (base64Image) =>
          compress(base64Image, uploadToServer)
        );
      });
    </script>
  </body>
</html>
